package com.shixj.ef.execute.base;

import com.shixj.ef.execute.HttpFetchExecute;
import com.shixj.ef.vo.FetchRequest;
import com.shixj.ef.vo.FetchResponse;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpUriRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;

/**
 * 负责发起请求获取dom
 * Created by shixj on 2017/7/18.
 */
public class BaseHttpFetchRunner implements Runnable {
    private static final Logger LOGGER = LoggerFactory.getLogger(BaseHttpFetchRunner.class);
    private HttpFetchExecute executor;

    public BaseHttpFetchRunner(HttpFetchExecute executor) {
        this.executor = executor;
    }


    public void sendFetch(FetchRequest request) {
        HttpUriRequest httpUriRequest = request.HttpUriRequestFactory();
        try {
            CloseableHttpResponse httpResponse = request.getHttpClient().execute(httpUriRequest);
            FetchResponse response = new FetchResponse(request, httpResponse);
            LOGGER.info(request.getFetchUrl() + "抓取成功");
            this.executor.putResponse(response);
        } catch (IOException e) {
            LOGGER.info(request.getFetchUrl() + "抓取失败");
            e.printStackTrace();
        }

    }

    @Override
    public void run() {
        while (this.executor.isRun())
            sendFetch(this.executor.takeRequest());
    }
}
